<?php
//水果大作战
namespace App\Http\Controllers\Api\Sgdzz;

use App\Http\Controllers\Controller;
use App\Models\Sgdzz\OrderDetailLog;
use App\Models\Sgdzz\OrderLog;
use App\Models\Sgdzz\Issue;
use App\Models\Sgdzz\PayLog;
use App\User;
use App\UserCoinLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SgdzzController extends Controller
{
    protected $wechat;

    private $reward_count = 2;

    public function __construct()
    {
        $this->wechat = app('wechat');
    }

    /**
     * 获取当前期号
     */
    public function getRunningIssue() {
        $currentUser = auth()->user();
        //获取实时数据
        $user = User::find($currentUser->id);
        $currentIssue = Issue::getRunningIssue();
        //获取用户当期购买水果信息汇总
        $paySumInfo = OrderDetailLog::getUserOrderDetailSumByType($currentIssue['id'], $user->id);
        return response()->json([
            'code'  => 0,
            'msg'   => 'success',
            'data'  => [
                'id' => $currentIssue['id'],
                'openAfter' => $currentIssue['openAfter'],
                'paySumInfo' => $paySumInfo,   //购买水果信息汇总
                'nickname' => $user->nickname,           /*用户昵称*/
                'pic' => $user->avatar,                  /*用户头像*/
                'balance' => $user->XYB,
            ],
        ]);
    }

    /**
     * 下单
     */
    public function doPay( Request $request ) {

        //数据结构
        //$payList   = [
        //    'type1' => 'gold1',
        //    'type2' => 'gold2',
        //    'type3' => 'gold3',
        //];
        $payList   = $request->input('payList');       //水果类型
        $issue     = (int)$request->input('issue');      //期号

        //绝对值处理
        foreach($payList as $type => $gold) {
            $payList[$type] = abs($gold);
        }

        $currentUser = auth()->user();

        //是否已封盘
        $currentIssue = Issue::getRunningIssue();

        //@todo begin
        //$issue = $currentIssue['id'];
        //$payList = [
        //    1 => rand(0, 5),
        //    2 => rand(0, 5),
        //    3 => rand(0, 5),
        //];
        //@todo end

        //获取实时数据
        $user = User::find($currentUser->id);
        //获取用户当期购买水果信息汇总
        $paySumInfo = OrderDetailLog::getUserOrderDetailSumByType($issue, $user->id);
        $returnData = [
            'id' => $currentIssue['id'],   //期号
            'openAfter' => $currentIssue['openAfter'],   //开奖时间
            'paySumInfo' => $paySumInfo,   //购买水果信息汇总
            'balance'   => $user->XYB,
        ];
        
        if($issue !== $currentIssue['id'] || ($currentIssue['openAfter'] <= 1)) {
            return response()->json([
                'code' => 1,
                'msg'  => '已封盘',
                'data' => $returnData,
            ]);
        }

        //增加历史获利的统计
        if(UserCoinLog::where('user_id', $currentUser->id)->where('bussiness_id', 5)->where('type', 1)->sum('coin') >= 500){
            return response()->json([
                'code' => 1,
                'msg'  => '请勿频繁操作',
                'data' => $returnData,
            ]);

            //发出警报
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "http://sms-api.luosimao.com/v1/send_batch.json");
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 8);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_USERPWD, 'api:key-5145112f10b704bbd5592f80402c77b5');
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, array('mobile_list' => '13726873311,13632403818', 'message' => '你好，发现异常情况。项目：水果大作战，UID：' . $currentUser->id . '，描述：用户通过游戏获利超过500元。【小妖传媒】'));
            $res = curl_exec($ch);
        }

        
        $goldSum = 0;
        foreach($payList as $type => $gold) {
            $goldSum += $gold;
        }

        if($user->XYB < $goldSum) {
            return response()->json([
                'code' => -1,
                'msg'  => '用户余额不足',
                'data' => $returnData,
                'balance' => $user->XYB,
            ]);
        }
        
        //每个用户每期只能购买50
        $userPayGold = OrderDetailLog::getUserPayGoldPerIssue($issue, $user->id);
        if($userPayGold >= 50 || $goldSum > 50) {
            return response()->json([
                'code' => 2,
                'msg'  => '每个用户每期只能投5000小妖币哦',
                'data' => $returnData,
            ]);
        }
        
        $code = 0;
        $msg = '下单成功';
        
        //下单
        try {

            $orderLimitMicrotime = microtime(true) * 10000;
            $now = time();

            //【重要】下面重复提交限制使用了第二个参数$orderLimitMicrotime
            $key = $user->id . '-' . $orderLimitMicrotime . '-' . implode('-', array_values($payList));

            //记录下单记录
            try {
                $orderLogModel              = new OrderLog();
                $orderLogModel->user_id     = $user->id;
                $orderLogModel->gold        = $goldSum;
                $orderLogModel->add_time    = $now;
                $orderLogModel->update_time = 0;
                $orderLogModel->issue       = $currentIssue['id'];
                $orderLogModel->key         = $key;
                $orderLogModel->pay_list    = json_encode($payList);
                $orderLogModel->save();
                $orderLogId = $orderLogModel->id;
            } catch ( \Exception $e) {
                throw new \Exception('下单错误，请勿重复提交', 1);
            }

            //查询上一次下单时间
            $preOrderLogItemArr = OrderLog::where('id', '<', $orderLogId)->where('user_id', $user->id)->orderBy('id', 'desc')->limit(1)->get()->toArray();
            if(!empty($preOrderLogItemArr[0])) {
                $keyParts = explode('-', $preOrderLogItemArr[0]['key']);
                $preOrderAddMicrotime = $keyParts[1];
                if($orderLimitMicrotime - $preOrderAddMicrotime < config('sgdzz.time_limit_microtime')) {  //上一次下单时间比下单停顿时间短，认为并发
                    OrderLog::find($orderLogId)->forceDelete();
                    throw new \Exception("请勿重复提交", 1);
                }
            }

            DB::beginTransaction();

            //获取新的用户信息
            $user = User::find($user->id);
            //记录扣款日志
            $payLogModel = new PayLog();
            $payLogModel->user_id = $user->id;
            $payLogModel->from_XYB = $user->XYB;
            $payLogModel->add_XYB = -$goldSum;
            $payLogModel->to_XYB = $user->XYB - $goldSum;
            $payLogModel->issue = $currentIssue['id'];
            $payLogModel->order_id = $orderLogId;
            $payLogModel->add_time = $now;
            $payLogModel->update_time = $now;
            $payLogModel->save();
            
            //扣减用户余额
            //config/type.php    9 => '水果大作战下单'
            $key = '9-'. $user->id . '-' . -$goldSum . '-' . $orderLimitMicrotime;
            //business表  5 => 水果大作战
            UserCoinLog::log( 5, $user->id, UserCoinLog::TYPE_XYB, -$goldSum, '水果大作战下单消耗', $key );

            //用户玩游戏状态更新
            $user->update(['status' => DB::raw('status|4')]);

            if(UserCoinLog::totalXyb( $user->id) < 0) {
                throw new \Exception('小妖币不足，请充值', 1);
            }

            //记录订单详情
            foreach($payList as $type => $gold) {
                if(empty($gold)) {
                    continue;
                }
                $orderDetailModel = new OrderDetailLog();
                $orderDetailModel->user_id = $user->id;
                $orderDetailModel->type = $type;
                $orderDetailModel->gold = $gold;
                $orderDetailModel->issue = $currentIssue['id'];
                $orderDetailModel->order_id = $orderLogId;
                $orderDetailModel->add_time = $now;
                $orderDetailModel->update_time = $now;
                $orderDetailModel->save();
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            $code = 1;
            $msg = $e->getMessage();
        }
        
        //获取用户当期购买水果信息汇总
        $paySumInfo = OrderDetailLog::getUserOrderDetailSumByType($currentIssue['id'], $user->id);

        //获取用户最新信息（余额）
        $user = User::find($user->id);
        
        //统计用户最新信息
        $returnData['paySumInfo'] = $paySumInfo;
        $returnData['balance'] = $user->XYB;
        
        //echo iconv('utf-8', 'gbk', $msg);
        //print_r([
        //    'code'  => $code,
        //    'data'  => $data,
        //]);

        //取得当前用户是否出现财神到
        $tmp_user_id = $user->id;
        $user = new \App\Tools\User\User();
        $returnData['isCaiShen'] = $user->getUserIsCoupon($tmp_user_id);

        return response()->json([
            'code'  => $code,
            'msg'   => $msg,
            'data'  => $returnData,
        ]);
    }

    /**
     * 撤销购买
     */
    public function unPay( Request $request ) {
        $currentUser = auth()->user();
        $issue = $request->input('issue');
        
        //@todo begin
        //$currentIssue = Issue::getRunningIssue();
        //$issue = $currentIssue['id'];
        //@todo end
        
        if(empty($issue)) {
            return response()->json([
                'code'  => 1,
                'msg'   => '缺少期号参数',
                'data'  => [],
            ]);
        }
        
        //是否已封盘
        $currentIssue = Issue::getRunningIssue();
        
        //期号没记录
        if( empty($currentIssue['id']) || ($currentIssue['id'] != $issue) ) {
            return response()->json([
                'code'  => 1,
                'msg'   => '该期没有正在进行中',
                'data'  => [],
            ]);
        }

        //期号正在开奖中
        if( $currentIssue['openAfter'] <= 0 ) {
            return response()->json([
                'code'  => 1,
                'msg'   => '该期正在开奖中',
                'data'  => $currentIssue,
            ]);
        }
        
        //撤销购买
        $code = 0;
        $msg = '撤销成功';
        try {
            DB::beginTransaction();

            //获取订单详情
            $orderDetail = OrderDetailLog::getUserOrderDetail($issue, $currentUser->id);
            
            //记录订单详情撤销
            $res = OrderDetailLog::where('issue', $currentIssue['id'])
                ->where('user_id', $currentUser->id)
                ->where('unpay', 0)
                ->update([
                    'unpay' => 1, 
                ]);
            if(empty($res)) {
                throw new \Exception('撤销失败', 1);
            }
            
            //退还金额
            $now = time();
            foreach( $orderDetail as $orderItem ) {
                //获取新的用户信息
                $user = User::find($currentUser->id);
                //记录奖励
                $payLogModel = new PayLog();
                $payLogModel->user_id = $currentUser->id;
                $payLogModel->from_XYB = $user->XYB;
                $payLogModel->add_XYB = $orderItem['gold'];
                $payLogModel->to_XYB = $user->XYB + $orderItem['gold'];
                $payLogModel->issue = $currentIssue['id'];
                $payLogModel->order_id = 0;
                $payLogModel->add_time = $now;
                $payLogModel->update_time = $now;
                $payLogModel->save();

                //config/type.php    9 => '水果大作战下单'
                $key = '9-'. $currentUser->id. '-' . $orderItem['order_id'] . '-' . $orderItem['type'] . '-' . $orderItem['gold'];

                //business表  5 => 水果大作战
                UserCoinLog::log( 5, $currentUser->id, UserCoinLog::TYPE_XYB, $orderItem['gold'], '水果大作战撤销返还', $key );
            }
            
            
            DB::commit();
        } catch ( \Exception $e ) {
            DB::rollBack();
            Log::debug($e);
            $code = 1;
            $msg = '撤销失败';
        }

        //获取用户当期购买水果信息汇总
        $paySumInfo = OrderDetailLog::getUserOrderDetailSumByType($currentIssue['id'], $currentUser->id);
        
        //获取用户最新信息（余额）
        $user = User::find($currentUser->id);

        //统计用户信息
        $data = [
            'openAfter' => $currentIssue['openAfter'],   //开奖时间
            'paySumInfo' => $paySumInfo,   //购买水果信息汇总
            'balance'   => $user->XYB,
        ];

        return response()->json([
            'code'  => $code,
            'msg'   => $msg,
            'data'  => $data,
        ]);
    }

    /**
     * 开奖结果查询接口
     */
    public function getIssueOpenResult( Request $request ) {
        $issue = $request->input('issue');
        $currentUser = auth()->user();

        $currentIssue = Issue::getRunningIssue();
        
        //@todo begin
        //$issue = $currentIssue['id'] - 1;
        //@todo end
        
        if(empty($issue)) {
            return response()->json([
                'code'  => 1,
                'msg'   => '缺少期号参数',
                'data'  => [],
            ]);
        }

        $winType = Issue::getIssueWinType($issue);
        
        switch($winType) {
            case 0: 
                $code = 1;
                $msg = '该期正在进行中';
                break;
            case -1:
                $code = 1;
                $msg = '该期不存在';
                break;
            case -2:
                $code = 1;
                $msg = '该期正在开奖中';
                break;
            default:
                $code = 0;
                $msg = '开奖成功';
                break;
        }

        if($code == 1) {
            return response()->json([
                'code'  => $code,
                'msg'   => $msg,
                'data'  => [],
            ]);
        }
        //获取用户当期中奖金额
        $winGold = OrderDetailLog::getUserWinGold($issue, $currentUser->id, $winType);
        
        //获取用户最新信息（余额）
        $user = User::find($currentUser->id);

        return response()->json([
            'code'  => $code,
            'msg'   => $msg,
            'data'  => [
                'id' => $currentIssue['id'],
                'openAfter' => $currentIssue['openAfter'],
                'balance'   => $user->XYB,
                'winType'  => $winType,
                'winGold'   => $winGold,
            ],
        ]);
    }
    
    /**
     * 创建下一期 @todo 临时接口
     */
    public function createNextIssue() {
        $code = 0;
        $msg  = '创建下一期成功';
        $issue = Issue::createNextIssue();

        if(empty($issue)) {
            $code = 1;
            $msg = '创建下一期失败';
        }
        return response()->json([
            'code'  => $code,
            'msg'   => $msg,
            'data'  => [
                'issue' => $issue,
            ],
        ]);
    }

    /**
     * 获取最近中奖信息
     */
    public function getLatestWinInfo( Request $request ) {
        $size = $request->input('size');
        
        $items = Issue::getLatestWinInfo($size);

        return response()->json([
            'code'  => 0,
            'msg'   => '获取最近中奖信息成功',
            'data'  => $items,
        ]);
    }

    /**
     * 获取最近中奖详情（用户昵称、中奖类型、中奖金额）
     */
    public function getLatestWinDetail( Request $request ) {
        $size = $request->input('size');
        $items = OrderDetailLog::getLatestWinDetail($size);
        return response()->json([
            'code'  => 0,
            'msg'   => '获取最近中奖详情成功',
            'data'  => $items,
        ]);
    }
    
}
